/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.bid.service.taskplugins  
 */
package com.apache.bid.service.taskplugins;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.apache.api.api.TimeTaskService;
import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.bid.common.BidCommonUtil;
import com.apache.bid.common.Constant;
import com.apache.bid.common.cache.BidCacheFactory;
import com.apache.bid.common.cache.BidCacheManager;
import com.apache.bid.entity.BidApply;
import com.apache.bid.entity.BidApplyHistory;
import com.apache.bid.entity.BidItemHistory;
import com.apache.bid.entity.BidPub;
import com.apache.bid.entity.BidSession;
import com.apache.bid.manager.BidApplyHistoryManager;
import com.apache.bid.manager.BidApplyManager;
import com.apache.bid.manager.BidItemHistoryManager;
import com.apache.bid.manager.BidPubManager;
import com.apache.bid.manager.BidSessionManager;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.rpc.util.LoadRpcService;

/**
 * description:  消息通知定时器
 * @author Hou Dayu 创建时间：2016-5-9  
 * 
 */
public class SendMessageTask implements PluginConnector, TimeTaskService {

	private transient static boolean SendMessageTaskMark = true;

	private BidItemHistoryManager bidItemHistoryManager;
	private BidApplyManager bidApplyManager;
	private BidApplyHistoryManager bidApplyHistoryManager;
	private BidSessionManager bidSessionManager;
	private BidPubManager bidPubManager;

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.zbxsoft.api.api.TimeTaskService#run()  
	 */
	@SuppressWarnings("rawtypes")
	public boolean run() {
		try {
			execute(new ParamsVo());
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public Object execute(ParamsVo param) throws Exception {
		ResultEntity entity = new ResultEntity();
		try {
			if (SendMessageTaskMark) {
				SendMessageTaskMark = false;
				BidItemHistory bih = new BidItemHistory();
				bih.setMsgStatus("1");
				param.setObj(bih);
				param.setMethodKey("");
				List<BidItemHistory> list = bidItemHistoryManager.getList(param);
				param = null;
				if (Validator.isEmpty(list))
					return entity;
				String type = SystemTools.getInstance().getValue("send_type");
				ParamsVo<BidItemHistory> vo = new ParamsVo<BidItemHistory>();
				for (BidItemHistory item : list) {
					boolean mark = false;
					if ("mobile".equalsIgnoreCase(type)) {
						mark = sendMobile(item);
					} else {
						mark = sendEmail(item);
					}
					if (mark) {
						item.setMsgStatus("2");
						vo.setObj(item);
						bidItemHistoryManager.editInfo(vo);
					}
				}
				vo = null;
			}
		} finally {
			SendMessageTaskMark = true;
		}
		return entity;
	}

	private boolean sendEmail(BidItemHistory item) {
		boolean mark = false;
		BidSession session = getSession(item);
		Map<String, Object> params = new HashMap<String, Object>();
		String email = "";
		if (Validator.isEmpty(session)) {
			BidApplyHistory apply = null;
			if (!Validator.isEmpty(session)
					&& Constant.getInstance().getSessionConfig("statusStop").equals(session.getStatus())) {
				apply = getBidApplyHistory("", session.getSessionId(), item.getUserName());
			} else {
				apply = getBidApplyHistory(item.getItemId(), "", item.getUserName());
			}
			if (Validator.isEmpty(apply))
				return true;
			email = apply.getEmail();

		} else {
			BidApply apply = getBidApply("", item.getSessionId(), item.getUserName());
			if (Validator.isEmpty(apply))
				return true;
			email = apply.getEmail();
		}
		if (Validator.isNull(email))
			return true;
		params.put("msgTitle", "【" + item.getItemName() + "】标的竞得通知");
		params.put("toUserEmail", email);
		params.put("toUserName", item.getUserName());
		BidPub pub = getPub(item.getItemId(), item.getSessionId());
		String content = "恭喜您竞得" + item.getItemName() + "标的，成交价款" + item.getLastValue() + item.getPriceUnit()
				+ "、交易服务费" + BidCommonUtil.getInstance().getCommission(item.getLastValue(), item.getIfFee(), pub)
				+ item.getPriceUnit() + "，请在三日内交款。";
		params.put("msgContent", content);
		params.put("msgType", "email");
		params.put("sysEname", "bidSystem");
		params.put("fromUserName", "平台");
		ResultEntity entity = LoadRpcService.service().doService("sendmsgService", "saveMsg", "XML", params, null);
		if ("true".equals(entity.getResult())) {
			mark = true;
		}
		return mark;
	}

	private boolean sendMobile(BidItemHistory item) {
		boolean mark = false;
		BidSession session = getSession(item);
		Map<String, Object> params = new HashMap<String, Object>();
		String mobile = "";
		if (Validator.isEmpty(session)) {
			BidApplyHistory apply = null;
			if (Constant.getInstance().getSessionConfig("statusStop").equals(session.getStatus())) {
				apply = getBidApplyHistory("", session.getSessionId(), item.getUserName());
			} else {
				apply = getBidApplyHistory(item.getItemId(), "", item.getUserName());
			}
			if (Validator.isEmpty(apply))
				return true;
			mobile = apply.getMobile();

		} else {
			BidApply apply = getBidApply("", item.getSessionId(), item.getUserName());
			if (Validator.isEmpty(apply))
				return true;
			mobile = apply.getMobile();//还没有对接移动接口
		}
		if (Validator.isNull(mobile))
			return true;
		BidPub pub = getPub(item.getItemId(), item.getSessionId());
		String content = "恭喜您竞得" + item.getItemName() + "标的，成交价款" + item.getLastValue() + item.getPriceUnit()
				+ "、交易服务费" + BidCommonUtil.getInstance().getCommission(item.getLastValue(), item.getIfFee(), pub)
				+ item.getPriceUnit() + "，请在三日内交款。";
		params.put("msgContent", content);
		params.put("msgType", "mobile");
		params.put("msgTitle", "【" + item.getItemName() + "】标的竞得通知");
		params.put("toUserMobile", mobile);
		params.put("toUserName", item.getUserName());
		params.put("sysEname", "bidSystem");
		params.put("fromUserName", "平台");
		ResultEntity entity = LoadRpcService.service().doService("sendmsgService", "saveMsg", "XML", params, null);
		if ("true".equals(entity.getResult())) {
			mark = true;
		}
		return mark;
	}

	private BidPub getPub(String itemId, String sessionId) {
		BidPub pub = new BidPub();
		if ("0".equals(sessionId)) {
			pub.setItemId(itemId);
		} else {
			pub.setSessionId(sessionId);
		}
		ParamsVo<BidPub> vo = new ParamsVo<BidPub>();
		vo.setObj(pub);
		pub = (BidPub) bidPubManager.getInfoById(vo);
		vo = null;
		return pub;
	}

	private BidSession getSession(BidItemHistory item) {
		BidSession session = null;
		if (!Constant.SETYPE_HD.equals(item.getSessionType())) {
			BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("session");
			session = (BidSession) cache.getCacheObjectByKey(BidCacheManager.session_prefix + item.getSessionId());
			if (Validator.isEmpty(session)) {
				ParamsVo<BidSession> vo = new ParamsVo<BidSession>();
				vo.setInfoId(item.getSessionId());
				session = (BidSession) bidSessionManager.getInfoById(vo);
			}
		}
		return session;
	}

	private BidApplyHistory getBidApplyHistory(String itemId, String sessionId, String userEname) {
		ParamsVo<BidApplyHistory> vo = new ParamsVo<BidApplyHistory>();
		BidApplyHistory apply = new BidApplyHistory();
		apply.setUserName(userEname);
		if (Validator.isNull(itemId) || "0".equals(itemId)) {
			apply.setSessionId(sessionId);
		} else {
			apply.setItemId(itemId);
		}
		vo.setObj(apply);
		List<BidApplyHistory> list = bidApplyHistoryManager.getList(vo);
		vo = null;
		if (Validator.isEmpty(list))
			return null;
		apply = list.get(0);
		return apply;
	}

	private BidApply getBidApply(String itemId, String sessionId, String userEname) {
		ParamsVo<BidApply> vo = new ParamsVo<BidApply>();
		BidApply apply = new BidApply();
		apply.setUserName(userEname);
		if (Validator.isNull(itemId)) {
			apply.setSessionId(sessionId);
		} else {
			apply.setItemId(itemId);
		}
		vo.setObj(apply);
		List<BidApply> list = bidApplyManager.getList(vo);
		vo = null;
		if (Validator.isEmpty(list))
			return null;
		apply = list.get(0);
		return apply;
	}

	public void setBidItemHistoryManager(BidItemHistoryManager bidItemHistoryManager) {
		this.bidItemHistoryManager = bidItemHistoryManager;
	}

	public void setBidApplyManager(BidApplyManager bidApplyManager) {
		this.bidApplyManager = bidApplyManager;
	}

	public void setBidApplyHistoryManager(BidApplyHistoryManager bidApplyHistoryManager) {
		this.bidApplyHistoryManager = bidApplyHistoryManager;
	}

	public void setBidSessionManager(BidSessionManager bidSessionManager) {
		this.bidSessionManager = bidSessionManager;
	}

	public void setBidPubManager(BidPubManager bidPubManager) {
		this.bidPubManager = bidPubManager;
	}
}
